import { Component, Vue } from 'vue-property-decorator'
import { Action } from 'vuex-class'
import { desensitization } from '@/lib/utils'
import styles from './PaymentOrder.less'
import DetailItem from '@/components/DetailItem'
import OperationCol from '@/components/OperationCol'
import AddressLayer from '@/modules/addressLayer'
import InvoiceInfo from './InvoiceInfo'
import {
  adminTypes,
  formatStatus,
  orgLicenseTypes,
  orgTypes,
  useTypes,
  userLicenseTypes,
  sealTypes,
  IStatus,
  payTypes,
  sealUseTimes,
} from '@/lib/sealFormat'

const formLabelWidth6: string = '96px'
const formLabelWidth7: string = '116px'

const detailData: any[] = [
  {
    key: 'eSealBasicInfo',
    title: '电子印章基本信息',
    single: true,
    child: [
      {
        key: 'sealCode',
        colLength: 12,
        labelWidth: formLabelWidth7,
        label: '印章编码',
        content: '',
      },
      {
        key: 'sealName',
        colLength: 12,
        labelWidth: formLabelWidth6,
        label: '电子印章名称',
        content: '',
      },
      {
        key: 'sealUseTypeName',
        colLength: 12,
        labelWidth: formLabelWidth7,
        label: '用章方式',
        content: '',
      },
      {
        key: 'sealTypeName',
        colLength: 12,
        labelWidth: formLabelWidth6,
        label: '电子印章类别',
        content: '',
      },
      {
        key: 'sealUseTimeName',
        colLength: 12,
        labelWidth: formLabelWidth7,
        label: '有效期',
        content: '',
      },
    ],
  },
  {
    key: 'sealOrgBasicInfo',
    title: '用章机构基本信息',
    child: [
      {
        key: 'applyOrganizeName',
        label: '机构名称',
        labelWidth: formLabelWidth7,
        content: '',
      },
      {
        key: 'applyOrganizeType',
        label: '机构类型',
        labelWidth: formLabelWidth6,
        content: '',
      },
      {
        key: 'applyOrganizeLicenseType',
        label: '证照类型',
        labelWidth: formLabelWidth7,
        content: '',
      },
      {
        key: 'applyOrganizeLicenseNumber',
        label: '证照号码',
        labelWidth: formLabelWidth6,
        content: '',
      },
      // { key: "organizeLevel", label: "行政等级", labelWidth: formLabelWidth3, content: "" }
    ],
  },
]

const receiver = {
  id: '',
  consigneeName: '',
  provinceName: '',
  cityName: '',
  areaName: '',
  areaDetail: '',
  consigneeMobile: '',
}

const amountList: any[] = [
  { label: '电子印章年服务费：', key: 1 },
  { label: 'Ukey硬件介质：', key: 2 },
  { label: '快递费：', key: 4 },
]
@Component({})
export default class PaymentOrder extends Vue {
  private detailData: any[] = []
  private sealUrl: string = ''
  private orderInfo: any = { payType: 1 }
  private orderPayTypes: any[] = []
  private orderInfoList: any[] = []
  private amountList: any[] = []
  private useType = 1 // 用章方式
  private isAll: boolean = false
  private sealApplyId?: any = ''
  private defaultData: any = {}
  private invoiceVisible: boolean = false
  private addressShow: boolean = false
  private addressData: any = {}
  private addible: number = 0 // 是否可新增
  private canPay: boolean = false
  private receiverList: any[] = []
  private receiver = null
  private hoverId = ''
  private invoiceInfo = {
    name: '增值税普通发票',
    type: '电子发票',
    orgName: '',
    orgCode: '',
  }
  private selectPayOrganize: string = ''
  private selectPayOrganizeInfo: any = {}
  private payOrganizeInfos: any[] = []
  private loading: boolean = false

  @Action('newApply/sealDetail') private sealDetail!: any
  @Action('paymentOrder/querySealApplyPayPreOrderInfo')
  private querySealApplyPayPreOrderInfo!: any
  @Action('paymentOrder/listMyDeliveryAddress')
  private listMyDeliveryAddress!: any
  @Action('paymentOrder/setAddressAsDefault') private setAddressAsDefault!: any
  @Action('paymentOrder/deleteDeliveryAddress')
  private deleteDeliveryAddress!: any
  @Action('applyPage/createOrder') private createOrder!: any

  protected render(h: any) {
    return (
      <div>
        <div class={styles.payOrder}>
          <div
            class={styles.seal}
            style={{
              background: `url(${
                (this.defaultData || {}).sealPicUrl
              }) center center / 127px no-repeat`,
            }}
          />
          <el-form hide-required-asterisk class={styles.detailForm}>
            {this.detailData &&
              this.detailData.map((item: any, index: number) => (
                <DetailItem
                  class={styles.detailItem}
                  data={item.child}
                  title={item.title}
                />
              ))}
          </el-form>
          <div class={styles.inputForm}>
            <p class={styles.panel}>付费方式</p>
            <el-radio-group
              v-model={this.orderInfo.payType}
              onChange={this.payTypeChange}
            >
              {payTypes &&
                payTypes.map((item: IStatus, i: number) => {
                  if (this.orderPayTypes.includes(item.id)) {
                    return <el-radio label={item.id}>{item.value}</el-radio>
                  }

                  return ''
                })}
            </el-radio-group>
            {this.orderInfo.payType === 2 && (
              <span>
                <p class={styles.panel}>统一付费方信息</p>
                <p class={styles.invoices}>
                  统一付费方：
                  <el-select
                    v-model={this.selectPayOrganize}
                    placeholder="请选择"
                    onChange={this.selectPayOrganizeChange}
                  >
                    {this.payOrganizeInfos.map((item: any) => {
                      return (
                        <el-option
                          key={item.payerOrganizeUUID}
                          label={item.payerOrganizeName}
                          value={item.payerOrganizeUUID}
                        />
                      )
                    })}
                  </el-select>
                  付费方管理员：
                  {this.selectPayOrganizeInfo.payerOrganizeContactName || ''}
                </p>
              </span>
            )}

            {this.defaultData.sealUseType === 1 && (
              <span>
                <p class={styles.panel}>
                  收货人信息
                  {this.orderInfo.payType === 1 && (
                    <el-button
                      class="ml10"
                      type="text"
                      onClick={this.addAddress}
                    >
                      新增收货地址
                    </el-button>
                  )}
                </p>
                {this.orderInfo.payType === 1 ? (
                  <div>
                    <el-table
                      class={styles.receiver}
                      data={
                        this.isAll
                          ? this.receiverList
                          : this.receiver
                          ? [this.receiver]
                          : []
                      }
                      show-header={false}
                      onCell-mouse-enter={(row: any) => {
                        this.hoverId = row.id
                      }}
                      onCell-mouse-leave={(row: any) => {
                        this.hoverId = ''
                      }}
                      onRow-click={this.selectRow}
                    >
                      <div slot="empty" />
                      <el-table-column
                        width="30"
                        {...{
                          scopedSlots: {
                            default: (scope: any) => {
                              return (
                                <el-radio-group v-model={this.receiver}>
                                  <el-radio label={scope.row} />
                                </el-radio-group>
                              )
                            },
                          },
                        }}
                      />
                      <el-table-column
                        prop="consigneeName"
                        label="姓名"
                        width="50"
                        show-overflow-tooltip
                      />
                      <el-table-column
                        prop="id"
                        show-overflow-tooltip
                        width="200"
                        {...{
                          scopedSlots: {
                            default: (scope: any) => {
                              return (
                                <span>
                                  {scope.row.provinceName}&nbsp;
                                  {scope.row.cityName}&nbsp;{scope.row.areaName}
                                </span>
                              )
                            },
                          },
                        }}
                      />
                      <el-table-column prop="areaDetail" width="400" />
                      <el-table-column
                        prop="consigneeMobile"
                        show-overflow-tooltip
                        width="100"
                      />
                      {/* <el-table-column prop="phone" width="100"/> */}
                      <el-table-column
                        prop="id"
                        show-overflow-tooltip
                        {...{
                          scopedSlots: {
                            default: (scope: any) => {
                              if (scope.row.defaultStatus === 1) {
                                return <p class={styles.default}>默认地址</p>
                              }
                            },
                          },
                        }}
                      />
                      <el-table-column
                        prop="operation"
                        label="操作"
                        align="right"
                        width="200"
                        {...{
                          scopedSlots: {
                            default: (scope: any) => {
                              return (
                                <OperationCol
                                  v-show={this.hoverId === scope.row.id}
                                  operations={this.filterOptions(scope.row)}
                                  showNum={4}
                                  row={scope.row}
                                  index={scope.$index}
                                />
                              )
                            },
                          },
                        }}
                      />
                    </el-table>
                    {(this.receiverList || []).length > 1 && (
                      <p class={styles.backup}>
                        {this.isAll ? (
                          <a class="cp mt20" onClick={() => this.backup(false)}>
                            收起地址
                            <i class="el-icon-arrow-up" />
                          </a>
                        ) : (
                          <a class="cp mt20" onClick={() => this.backup(true)}>
                            更多地址
                            <i class="el-icon-arrow-down" />
                          </a>
                        )}
                      </p>
                    )}
                  </div>
                ) : (
                  <span>
                    <p class="info">
                      <i class="el-icon-warning" />
                      UKey硬件介质将会直接邮寄至付费方负责人处。请申请人主动联络付费方负责人，现场领取UKey硬件介质。
                    </p>
                    <div class={styles.invoices}>
                      <p>
                        收货人信息：
                        {this.selectPayOrganizeInfo.payerOrganizeContactName}
                      </p>
                      <p>
                        {desensitization(
                          this.selectPayOrganizeInfo.payerOrganizeContactPhone
                        )}
                      </p>
                      <p>
                        收货地址：
                        {
                          this.selectPayOrganizeInfo
                            .payerOrganizeShippingAddress
                        }
                      </p>
                      <p>
                        详细地址：
                        {this.selectPayOrganizeInfo.payerOrganizeAddressDetail}
                      </p>
                    </div>
                  </span>
                )}
              </span>
            )}
            {this.orderInfo.payType === 1 && (
              <span>
                <p class={styles.panel}>发票信息</p>
                {this.invoiceInfo && (
                  <div class={styles.invoices}>
                    <p>{this.invoiceInfo.name}</p>
                    <p>{this.invoiceInfo.type}</p>
                    <p class="org">{this.invoiceInfo.orgName}</p>
                    <p>{this.invoiceInfo.orgCode}</p>
                    <p>
                      <el-button type="text" onClick={this.editInvoices}>
                        修改
                      </el-button>
                    </p>
                  </div>
                )}
              </span>
            )}

            <p class={styles.panel}>订单明细</p>
            <div class={styles.orderDetail}>
              <div class={styles.lists}>
                {this.getPayDetail().map(
                  (amount: any, index: number) =>
                    (amount.goodsType === 1 ||
                      (amount.goodsType === 2 &&
                        this.defaultData.sealUseType === 1) ||
                      (amount.goodsType === 4 &&
                        this.defaultData.sealUseType === 1 &&
                        this.orderInfo.payType === 1)) && (
                      <p class={styles.detail}>
                        <p class={styles.label}>{amount.label}</p>
                        <p
                          class={{
                            [styles.value]: true,
                            [styles.isDiscount]: amount.price === '0.00',
                          }}
                        >
                          <span>
                            ￥
                            {amount.price / amount.quantity
                              ? (amount.price / amount.quantity).toFixed(2)
                              : '35.00'}
                          </span>
                          {amount.price === '0.00' && (
                            <p class={styles.discount}>优惠</p>
                          )}
                        </p>
                        {amount.quantity && amount.goodsType !== 4 && (
                          <p class={styles.number}>x{amount.quantity}</p>
                        )}
                      </p>
                    )
                )}
              </div>
              <div class={styles.amountPart}>
                <p class={styles.amount}>
                  应付总额：
                  <span class={styles.number}>￥{this.getAllAmount()}</span>
                </p>
                {this.defaultData.sealUseType === 1 &&
                  (this.orderInfo.payType === 1 ? (
                    <p class={styles.address}>
                      寄送至：{(this.receiver || receiver).provinceName}&nbsp;
                      {(this.receiver || receiver).cityName}
                      &nbsp;
                      {(this.receiver || receiver).areaName}&nbsp;
                      {(this.receiver || receiver).areaDetail}
                      &nbsp;&nbsp;收件人：
                      {(this.receiver || receiver).consigneeName}&nbsp;&nbsp;
                      {(this.receiver || receiver).consigneeMobile}
                    </p>
                  ) : (
                    <p class={styles.address}>
                      寄送至：
                      {this.selectPayOrganizeInfo.payerOrganizeShippingAddress}
                      &nbsp;
                      {this.selectPayOrganizeInfo.payerOrganizeAddressDetail}
                      &nbsp;&nbsp;收件人：
                      {this.selectPayOrganizeInfo.payerOrganizeContactName}
                      &nbsp;&nbsp;
                      {desensitization(
                        this.selectPayOrganizeInfo.payerOrganizeContactPhone
                      )}
                    </p>
                  ))}
              </div>
            </div>
          </div>
          {this.canPay && this.orderPayTypes.length > 0 && (
            <div class={styles.footer}>
              <el-button onClick={this.notPay}>暂不支付</el-button>
              <el-button
                type="primary"
                onClick={this.toPay}
                loading={this.loading}
              >
                前往支付
              </el-button>
            </div>
          )}
        </div>
        <InvoiceInfo
          visible={this.invoiceVisible}
          defaultData={this.invoiceInfo}
          onVisibleChange={(val: boolean) => {
            this.invoiceVisible = val
          }}
          onSubmit={(val: any) => {
            this.invoiceInfo.orgName = val.orgName
            this.invoiceInfo.orgCode = val.licenseNumber
          }}
        />
        <AddressLayer
          show={this.addressShow}
          {...{
            on: {
              'update:show': (val: boolean) => {
                this.addressShow = val
              },
              'update:data': (val: any) => {
                this.addressData = val
              },
            },
          }}
          data={this.addressData}
          onSuccess={this.addressSuccess}
        />
      </div>
    )
  }

  private mounted() {
    this.sealApplyId = this.$route.query.id || ''
    if (!this.sealApplyId) return
    this.sealApplyId = parseInt(this.sealApplyId)
    this.getSealDetail()
    // this.detailData = detailData;
    this.getPreOrder()
    this.getMyAddressList()
    // this.receiver = this.receiverList[0];
    // this.amountList = amountList;
  }

  private getSealDetail() {
    this.sealDetail(this.sealApplyId).then((res: any) => {
      this.canPay = res.sealApplyStatus === 26 // 待支付状态
      this.invoiceInfo.orgName = res.applyOrganizeName
      this.invoiceInfo.orgCode = res.applyOrganizeLicenseNumber
      this.defaultData = {
        ...res,
        agentLicenseType: formatStatus(userLicenseTypes, res.agentLicenseType),
        applyOrganizeLevel: formatStatus(adminTypes, res.applyOrganizeLevel),
        applyOrganizeLicenseType: formatStatus(
          orgLicenseTypes,
          res.applyOrganizeLicenseType
        ),
        applyOrganizeType: formatStatus(orgTypes, res.applyOrganizeType),
        confirmOrganizeLicenseType: formatStatus(
          orgLicenseTypes,
          res.confirmOrganizeLicenseType
        ),
        sealTypeName: formatStatus(sealTypes, res.sealType),
        sealUseTypeName: formatStatus(useTypes, res.sealUseType),
        agentLicenseNumberDes: desensitization(res.agentLicenseNumber || ''),
        agentMobileDes: desensitization(res.agentMobile || ''),
        sealUseTimeName: formatStatus(sealUseTimes, res.sealUseTime),
      }
      detailData.forEach((detail: any) => {
        detail.child.forEach((item: any) => {
          item.content = this.defaultData[item.key]
        })
      })
      this.detailData = detailData
      if (!this.canPay) {
        this.$message.error('当前印章申请不处于待支付状态')

        return
      }
      if (!!res.payOrderId) {
        this.$message.info('订单已存在')
        this.$router.push({
          name: 'orderConfirm',
          query: { orderId: res.payOrderId, sealApplyId: this.sealApplyId },
        })
      }
    })
  }

  private getPreOrder() {
    this.querySealApplyPayPreOrderInfo(this.sealApplyId).then((res: any) => {
      this.orderPayTypes = []
      this.orderInfoList = res.map((order: any) => {
        const goods = (order.goods || []).map((good: any) => {
          return {
            ...good,
            ...(amountList.find(
              (amount: any) => amount.key === good.goodsType
            ) || {}),
          }
        })

        return {
          ...order,
          goods,
        }
      })

      res.forEach((element: any) => {
        this.orderPayTypes.push(element.payType)
        if (element.payType === 2) {
          this.payOrganizeInfos = this.payOrganizeInfos.concat(
            element.payOrganizeInfos
          )
        }
      })
      this.orderInfo.payType = this.orderPayTypes.includes(2) ? 2 : 1
      this.selectPayOrganize =
        (this.payOrganizeInfos[0] || {}).payerOrganizeUUID || ''
      this.selectPayOrganizeInfo = this.payOrganizeInfos[0] || {}
    })
  }

  private payTypeChange(val: number) {}

  private selectPayOrganizeChange(val: string) {
    this.selectPayOrganizeInfo =
      (this.payOrganizeInfos || []).find(e => e.payerOrganizeUUID === val) || {}
  }

  private selectRow(row: any, column: any) {
    if (
      column.property !== 'operation' &&
      (this.receiver || { id: '' }).id !== row.id
    ) {
      // 操作点击不选中&&选中之前的不触发backup
      this.receiver = row
      this.backup(false)
      this.hoverId = ''
      this.sortReceiverList()
    }
  }

  private sortReceiverList() {
    // 排序收货人地址信息
    this.receiverList = [this.receiver].concat(
      (this.receiverList || [])
        .filter(item => item.id !== (this.receiver || { id: '' }).id)
        .sort((a: any, b: any) => b.defaultStatus - a.defaultStatus)
    )
  }

  private backup(isAll: boolean) {
    this.isAll = isAll
    if (isAll) {
      this.getMyAddressList()
    }
  }

  private notPay() {
    this.$router.back()
  }

  private toPay() {
    if (
      this.defaultData.sealUseType === 1 &&
      this.orderInfo.payType === 1 &&
      !(this.receiver || { id: '' }).id
    ) {
      // UKEY自付费未选中收货地址
      this.$message.error('请选择收货人信息及收货地址')

      return
    }

    if (this.orderInfo.payType === 2 && !this.selectPayOrganize) {
      // 统一付费方判断
      this.$message.error('请选择统一付费方')

      return
    }

    if (
      this.orderInfo.payType === 1 &&
      (!this.invoiceInfo.orgName || !this.invoiceInfo.orgCode)
    ) {
      // 自付费发票信息判断
      this.$message.error('请完善发票信息')

      return
    }
    this.loading = true
    this.createOrder({
      sealApplyId: this.sealApplyId,
      deliveryAddressId:
        this.defaultData.sealUseType === 1 && this.orderInfo.payType === 1
          ? (this.receiver || { id: '' }).id
          : undefined,
      expressFee:
        (this.getPayDetail().find((item: any) => item.goodsType === 4) || {})
          .price || 0,
      invoiceTitle:
        this.orderInfo.payType === 1 ? this.invoiceInfo.orgName : undefined,
      taxpayerIdentityNumber:
        this.orderInfo.payType === 1
          ? (this.invoiceInfo.orgCode || '').toLocaleUpperCase()
          : undefined,
      payType: this.orderInfo.payType,
      payerOrganizeUUID:
        this.orderInfo.payType === 2
          ? this.selectPayOrganize
          : this.defaultData.applyOrganizeUuid,
    })
      .then((res: any) => {
        this.loading = false
        // this.$message.success("支付成功")
        this.$router.push({
          name: 'orderConfirm',
          query: { orderId: res.payOrderId, sealApplyId: this.sealApplyId },
        })
      })
      .catch((e: any) => {
        this.loading = false
      })
  }
  get operations() {
    const btns: any[] = [
      {
        id: 1,
        text: '设为默认地址',
        onClick: (index: number, rows: any, e: any) => {
          this.setAddressAsDefault({ id: rows.id }).then((res: any) => {
            this.$message.success('设置成功')
            this.getMyAddressList()
          })
        },
      },
      {
        id: 2,
        text: '修改',
        onClick: (index: number, rows: any) => {
          this.updateAddress(rows)
        },
      },
      {
        id: 3,
        text: '删除',
        onClick: (index: number, rows: any) => {
          this.$confirm(
            '是否确认进行此操作，您将无法恢复这些数据',
            '确认删除',
            {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              customClass: 'confirm-dialog',
              type: 'warning',
            }
          )
            .then(() => {
              this.deleteDeliveryAddress({ id: rows.id }).then((res: any) => {
                this.$message({
                  type: 'success',
                  message: '删除成功',
                })
                this.getMyAddressList()
              })
            })
            .catch(() => {})
        },
      },
    ]

    return btns
  }

  private getPayDetail() {
    const orderInfo =
      this.orderInfoList.find(e => e.payType === this.orderInfo.payType) || {}

    return orderInfo.goods || []
  }

  /**
   *
   * @param data 地址信息，可以为空，添加时会传入
   */
  private getMyAddressList(data?: any) {
    return new Promise((resolve, reject) => {
      this.listMyDeliveryAddress()
        .then((res: any) => {
          this.receiverList = res.list
          // this.addible = res.addible;
          if (!this.receiver) {
            this.receiver = this.receiverList[0] || null
          } else {
            if (data) {
              // 让新添加的地址默认选中
              // 当列表中的地址信息，地区代码与地址详情相同时
              this.receiver = this.receiverList.find(
                item =>
                  item.consigneeName === data.consigneeName &&
                  item.fullCode === data.fullCode &&
                  item.areaDetail === data.areaDetail
              )
            } else {
              this.receiver =
                this.receiverList.find(
                  e => e.id === (this.receiver || { id: '' }).id
                ) || null
            }
          }
          this.sortReceiverList()
          resolve()
        })
        .catch((e: any) => {
          reject()
        })
    })
  }

  private getAllAmount() {
    const orderInfo =
      this.orderInfoList.find(e => e.payType === this.orderInfo.payType) || {}

    return orderInfo.payAmount || 0
  }

  private filterOptions(row: any) {
    if (row.defaultStatus === 1) {
      // 默认只能修改
      return [this.operations[1]]
    }
    if (row.id === (this.receiver || { id: '' }).id) {
      // 选中的不能删除
      return [this.operations[0], this.operations[1]]
    }

    return this.operations
  }

  private editInvoices() {
    this.invoiceVisible = true
  }

  private addressSuccess(val: any) {
    console.log(val)
    this.getMyAddressList(val)
  }

  private addAddress() {
    this.addressData = {}
    this.addressShow = true
  }

  private updateAddress(row: any) {
    this.addressData = row
    this.addressShow = true
  }
}
